package com.minminaya.source;

public class Algorithm_14 {


    public static class ListNode {
        int value;
        ListNode next;
    }

    public static ListNode merge(ListNode head1, ListNode head2) {

        //链表只有一个元素的情况
        if (head1 == null) {
            return head2;
        }

        if (head2 == null) {
            return head1;
        }


        ListNode root = new ListNode();

        //合并后的新链表的尾部节点
        ListNode pointer = root;

        while (head1 != null && head2 != null) {
            if(head1.value < head2.value){
                pointer.next = head1;
                head1 = head1.next;
            }

            if(head1.value > head2.value){
                pointer.next = head2;
                head2 = head2.next;
            }

            pointer = pointer.next;

        }

        //处理末尾，哪条链表剩就将其合并到pointer
        if(head1 !=null){
            pointer.next = head1;
        }

        if(head2 !=null){
            pointer.next = head2;
        }
        return root.next;
    }


}
